# coding=utf-8

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.core import serializers
from django.utils import simplejson
from django.core.paginator import Paginator
from models import Catalog,Item

#全局变量
#分页限制
PAGE_SIZE = 50

#首页视图
def index(request,page=1):
    post_lists = Item.objects.all()
    paginator = Paginator(post_lists,PAGE_SIZE)
    try:
        posts = paginator.page(page)
    except:
        posts = paginator.page(paginator.num_pages)
    return render_to_response('home/index.html',{'posts':posts})

#商品分类视图
def cat(request,ename='Clothing-and-Underwear',page=1):
    try:
        cat = Catalog.objects.get(ename=ename)
    except:
        cat = Catalog.objects.all()[0]
    print 'catalog name :',cat.name
    post_list = Item.objects.filter(catalog=cat)
    paginator = Paginator(post_list,PAGE_SIZE)
    try:
        posts = paginator.page(page)
    except:
        posts = paginator.page(paginator.num_pages)
    return render_to_response('home/index.html',{'posts':posts})
    

#以下为API视图，返回JSON格式数据
def getCat(request):
    data = serializers.serialize('json',Catalog.objects.all())
    return HttpResponse(simplejson.dumps(data,ensure_ascii=False),mimetype='application/json')
#增加喜欢数
def incLike(request):
    _id = request.GET.get('id')
    flag = False
    try:
        item = Item.objects.get(id=_id)
        item.liked=(item.liked+1)
        item.save()
        flag = True
    except:
        print 'increase liked error:id='+_id
    return HttpResponse(flag)

#增加点击数
def incClick(request):
    _id = request.GET.get('id')
    flag = False
    try:
        item = Item.objects.get(id=_id)
        item.clicked=(item.clicked+1)
        item.save()
        flag = True
    except:
        print 'increase clicked error:id='+_id
    return HttpResponse(flag)

